

/*
 *  ME_218_I2C.h
 *  ArduinoOnXcode
 *
 *  Created by Rick Miley on 3/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

/*
 twi.h - TWI/I2C library for Wiring & Arduino
 Copyright (c) 2006 Nicholas Zambetti.  All right reserved.
 
 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.
 
 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */


#ifndef ME218_I2C_HEADER_FILE		// make sure I2C header file is included only once
#define ME218_I2C_HEADER_FILE

#include <compat/twi.h>


#define CPU_FREQ 16000000L

#define TWI_FREQ 100000L

#define TWI_BUFFER_LENGTH 32

#define TWI_READY 0
#define TWI_MRX   1
#define TWI_MTX   2
#define TWI_SRX   3
#define TWI_STX   4

void twi_init(void);
void twi_setAddress(uint8_t);
uint8_t twi_readFrom(uint8_t, uint8_t*, uint8_t);
uint8_t twi_writeTo(uint8_t, uint8_t*, uint8_t, uint8_t);
uint8_t twi_transmit(uint8_t*, uint8_t);
void twi_attachSlaveRxEvent( void (*)(uint8_t*, int) );
void twi_attachSlaveTxEvent( void (*)(void) );
void twi_reply(uint8_t);
void twi_stop(void);
void twi_releaseBus(void);


// ======================== TWI ===========================


#define TWI_BUFFER_LENGTH 32

static uint8_t				TWI_rxBuffer[TWI_BUFFER_LENGTH];
static uint8_t				TWI_rxBufferIndex;
static uint8_t				TWI_rxBufferLength;

static uint8_t				TWI_txAddress;
static uint8_t				TWI_txBuffer[TWI_BUFFER_LENGTH];
static uint8_t				TWI_txBufferIndex;
static uint8_t				TWI_txBufferLength;

static uint8_t				TWI_transmitting;

// =================================

static volatile uint8_t		twi_state;
static uint8_t				twi_slarw;

static void					(*twi_onSlaveTransmit)(void);
static void					(*twi_onSlaveReceive)(uint8_t*, int);

static uint8_t				twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t		twi_masterBufferIndex;
static uint8_t				twi_masterBufferLength;

static uint8_t				twi_txBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t		twi_txBufferIndex;
static volatile uint8_t		twi_txBufferLength;

static uint8_t				twi_rxBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t		twi_rxBufferIndex;

static volatile uint8_t twi_error;

// =====================


static void (*TWI_user_onRequest)(void);
static void (*TWI_user_onReceive)(int);
static void TWI_onRequestService(void);
static void TWI_onReceiveService(uint8_t*, int);

#endif // header file









